package com.wurd.test.controller;

import com.alibaba.fastjson.JSONObject;
import com.wurd.test.exception.WxException;
import com.wurd.test.wx.utils.TokenUtils;
import com.wurd.test.wx.token.Cache;
import com.wurd.test.wx.token.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/proxy/wx")
public class WxGzhProxyController {

    @Autowired
    private Cache cache;

    @GetMapping(value = "/getMaterialList/{appId}")
    public Object getMaterialList(@PathVariable String appId) {
        System.out.println("getMaterialList");
        try {
            Token preAuthCode = cache.getAppAuthRefreshToken().get(appId);
            if (preAuthCode == null) {
                return "请先授权: /wx/authQr";
            }
            if (!TokenUtils.verifyToken(preAuthCode)) {
                return "授权过期: /wx/authQr";
            }
            JSONObject preParam = new JSONObject();
            preParam.put("access_token", preAuthCode.getToken());
            JSONObject preBody = new JSONObject();
            preBody.put("type", "image");
            preBody.put("offset", 0);
            preBody.put("count", 10);
            JSONObject obj = TokenUtils.postMaterialList(preParam, preBody);
            return obj;
        } catch (WxException e) {
            e.printStackTrace();
            return e.getMsg();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
